<template>
  <el-container>
    <el-header height="40px">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <router-link to="/system/menu">
            <el-button type="primary" size="mini">菜单管理</el-button>
          </router-link>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="refreshMenuHandler"
            >刷新菜单</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="reloadConf"
            >重新加载配置</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="uploadHandler"
            >上传安装包</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="flush"
          ></el-button>
        </el-col>
      </el-row>
    </el-header>
    <el-container>
      <el-aside width="200px">
        <Menu ref="menu" @on-node-click="handleNodeClick"></Menu>
      </el-aside>
      <el-main>
        <el-collapse v-model="activeNames">
          <el-collapse-item
            :name="deployWorker.deployName"
            :key="deployWorker.deployName"
            v-for="deployWorker in deployWorkers"
          >
            <template slot="title">
              <el-button
                type="primary"
                size="mini"
                @click.stop="removeDeploy(deployWorker)"
                plain
                >移除安装包</el-button
              >
              <el-button
                type="primary"
                size="mini"
                @click.stop="conf(deployWorker.deployName)"
                plain
                >配置</el-button
              >
              <span v-if="deployWorker.path" class="deployName"
                >路径:{{ deployWorker.path }}，安装包:{{
                  deployWorker.deployName
                }}</span
              >
              <span v-if="!deployWorker.path" class="deployName"
                >路径:/，安装包:{{ deployWorker.deployName }}</span
              >
            </template>
            <el-card
              class="box-card"
              v-for="group in deployWorker.groupWorkers"
              :key="group.groupName"
            >
              <div slot="header" class="clearfix">
                <span
                  >组名:{{ group.groupName }},描述:{{ group.groupDesc }}</span
                >
              </div>
              <el-table :data="group.workers">
                <el-table-column
                  prop="index"
                  label="序号"
                  class-name="el-table-column"
                />
                <el-table-column
                  prop="workerName"
                  label="进程名称"
                  class-name="el-table-column"
                />
                <el-table-column
                  label="主机"
                  prop="host"
                  align="center"
                  min-width="120"
                  class-name="el-table-column"
                />
                <el-table-column
                  label="是否在线"
                  align="center"
                  class-name="el-table-column"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-circle-check"
                      v-show="scope.row.online"
                      style="color: limegreen"
                      >在线</el-button
                    >
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-circle-close"
                      v-show="!scope.row.online"
                      disabled
                      >不在线</el-button
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  label="进程编号"
                  prop="pid"
                  align="center"
                  class-name="el-table-column"
                />
                <el-table-column
                  label="内存"
                  align="center"
                  min-width="70"
                  class-name="el-table-column"
                >
                  <template slot-scope="scope">{{ mem(scope.row) }}</template>
                </el-table-column>
                <el-table-column
                  label="线程"
                  prop="liveThreadCount"
                  align="center"
                  class-name="el-table-column"
                />
                <el-table-column
                  label="上线时间"
                  prop="startTime"
                  align="center"
                  min-width="150"
                  class-name="el-table-column"
                />
                <el-table-column
                  label="操作"
                  align="center"
                  min-width="150"
                  class-name="small-padding fixed-width el-table-column"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      @click="startHandler(scope.row)"
                      >启动</el-button
                    >
                    <el-button
                      size="mini"
                      type="text"
                      @click="stopHandler(scope.row)"
                      >停止</el-button
                    >
                    <el-button
                      size="mini"
                      type="text"
                      @click="logHandler(scope.row)"
                      >日志</el-button
                    >
                    <!--
                    <el-button
                      size="mini"
                      type="text"
                      @click="infoHandler(scope.row)"
                      >详情</el-button
                    >
                    -->
                    <el-button
                      size="mini"
                      type="text"
                      @click="uiHandler(scope.row)"
                      v-if="scope.row.ui"
                      :title="scope.row.ui"
                      >UI</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-collapse-item>
        </el-collapse>
      </el-main>
    </el-container>

    <!--弹出对话框-->
    <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-form-item label="进程组" prop="groupName">
            {{ form.groupName }}
          </el-form-item>
          <el-form-item label="进程名称" prop="workerName">
            {{ form.workerName }}
          </el-form-item>
          <el-form-item label="进程编号" prop="index">
            <el-input-number
              v-model="form.index"
              controls-position="right"
              :min="1"
            />
          </el-form-item>
          <el-form-item label="强制" prop="force" v-show="form.forceShow">
            <el-switch v-model="force"></el-switch>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <Deploy
      :uploadOpenP="uploadOpen"
      :pathP="uploadPath"
      :deployNamesP="deployNames"
      @on-upload-success="uploadSuccess"
      @on-close="uploadClose"
    ></Deploy>
  </el-container>
</template>
<script>
import {
  getWorkerList,
  getWorkerListByPath,
  startWorker,
  stopWorker,
  getDeployList,
  loadConf,
  removeDeploy,
} from "@/api/console";
import Menu from "@/views/components/Menu";
import Deploy from "@/views/components/Deploy";
export default {
  components: {
    Menu,
    Deploy,
  },
  data() {
    return {
      deployWorkers: [],
      activeNames: [],
      path: "",
      //上传
      uploadOpen: false,
      deployNames: [],
      uploadPath: "",
      // 弹出层
      title: "",
      open: false,
      form: {},
      opera: "",
      force: false,
    };
  },
  created() {
    console.log(this.path);
    this.deployWorkerList();
  },
  methods: {
    deployWorkerList() {
      this.loading = true;
      let fun;
      if (this.path) {
        fun = getWorkerListByPath;
      } else {
        fun = getWorkerList;
      }
      fun(this.path)
        .then((res) => {
          this.deployWorkers = res.data;
          this.loading = false;
          if (this.deployWorkers.length > 0) {
            this.activeNames = [];
            for (let i = 0; i < this.deployWorkers.length; i++) {
              this.activeNames[i] = this.deployWorkers[i].deployName;
            }
          }
        })
        .catch((msg) => {
          this.loading = false;
        });
    },
    handleNodeClick(data) {
      this.path = data.path;
      this.deployWorkerList();
    },
    uploadHandler() {
      if (!this.path) {
        this.msgSuccess("请选择菜单上传");
      } else {
        getDeployList()
          .then((res) => {
            this.deployNames = res.data;
            this.uploadOpen = true;
            this.uploadPath = this.path;
          })
          .catch((msg) => {});
      }
    },
    refreshMenuHandler() {
      this.$refs.menu.menuTreeList();
    },
    uploadSuccess(file, fileList) {
      loadConf()
        .then((res) => {
          this.msgSuccess("操作成功");
          this.deployWorkerList();
        })
        .catch((msg) => {});
    },
    uploadClose() {
      this.uploadOpen = false;
    },
    flush() {
      this.deployWorkerList();
    },
    conf(deployName) {
      this.$store.commit("conf/SET_DEPLOY_NAME", deployName);
      this.$router.push("/service/conf");
    },
    startHandler(row) {
      this.form = { ...row };
      this.force = false;
      this.form.forceShow = false;
      this.open = true;
      this.title = "启动进程";
      this.opera = "start";
    },
    stopHandler(row) {
      this.form = { ...row };
      this.force = false;
      this.form.forceShow = true;
      this.open = true;
      this.title = "停止进程";
      this.opera = "stop";
    },
    logHandler(row) {
      const regionName = row.regionName;
      const deployName = row.deployName;
      const groupName = row.groupName;
      const workerName = row.workerName;
      const index = row.index;
      const host = row.host;
      const dir = "/" + regionName + "/" + deployName;
      const path =
        row.homePath +
        "/logs/" +
        regionName +
        "/" +
        deployName +
        "/" +
        groupName +
        "-" +
        workerName +
        "-" +
        index +
        ".log";
      if (host) {
        this.$store.commit("log/SET_HOST", host);
      } else {
        this.$store.commit("log/SET_HOST", "");
      }
      this.$store.commit("log/SET_DIR", dir);
      if (row.homePath) {
        this.$store.commit("log/SET_PATH", path);
      } else {
        this.$store.commit("log/SET_PATH", "");
      }
      this.$router.push("/service/log");
    },
    uiHandler(row) {
      if (!row.ui) {
        return;
      } else if (row.ui === "gateway") {
        this.$router.push(
          "/service/gateway?deployName=" +
            row.deployName +
            "&groupName=" +
            row.groupName +
            "&workerName=" +
            row.workerName +
            "&index=" +
            row.index
        );
      } else {
        open(row.ui);
      }
    },
    // 取消按钮
    cancel() {
      this.form = {};
      this.open = false;
    },
    /** 提交按钮 */
    submitForm: function () {
      if (this.opera === "start") {
        startWorker(
          this.form.regionName,
          this.form.deployName,
          this.form.groupName,
          this.form.workerName,
          this.form.index
        )
          .then((res) => {
            this.msgSuccess("操作成功，请刷新");
            this.open = false;
          })
          .catch((msg) => {});
      } else if (this.opera === "stop") {
        if (!this.form.host) {
          this.msgError("未启动");
          return;
        }
        console.log(this.force);
        stopWorker(
          this.form.regionName,
          this.form.deployName,
          this.form.groupName,
          this.form.workerName,
          this.form.index,
          this.force
        )
          .then((res) => {
            this.msgSuccess("操作成功，请刷新");
            this.open = false;
          })
          .catch((msg) => {});
      }
    },
    reloadConf() {
      this.$confirm("是否确认重新加载", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return loadConf();
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.deployWorkerList();
        });
    },
    removeDeploy(deployWorker) {
      for (let i = 0; i < deployWorker.groupWorkers.length; i++) {
        const workers = deployWorker.groupWorkers[i].workers;
        for (let j = 0; j < workers.length; j++) {
          if (workers[j].online) {
            this.msgError("请先停止所有进程");
            return;
          }
        }
      }
      this.$confirm("是否确认移除安装包", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return removeDeploy(deployWorker.deployName);
        })
        .then(() => {
          return loadConf();
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.deployWorkerList();
        });
    },
    mem(row) {
      const heapMemory = (parseInt(row.heapMemory * 10) * 1.0) / 10 + "M";
      //const nonHeapMemory=(parseInt(row.nonHeapMemory * 10) * 1.0) / 10 + "M";
      return heapMemory;
    },
    infoHandler(row) {},
  },
};
</script>

<style>
.main-container .el-header {
  border-bottom: 1px solid #e6ebf5;
  padding: 5px 10px;
}

.el-aside {
  background-color: #fff;
  padding: 1px 0px;
  margin: 0px;
  min-height: 500px;
}

.el-collapse-item__header {
  background-color: ghostwhite;
}

.el-collapse-item__header:before,
.el-collapse-item__header :after {
  display: table;
  content: "";
}

.el-collapse-item__header:after {
  clear: both;
}

.deployName {
  width: 400px;
  margin-left: 20px;
}

.box-card {
  margin-top: 5px;
}

.el-card__body {
  padding: 0px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.el-table__row .el-table-column,
.el-table__header .el-table-column {
  padding: 2px 0;
}
</style>